/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snda.lidejia.jobflow.taskhandler.ftp;

import com.snda.lidejia.jobflow.exception.JobFlowException;
import com.snda.lidejia.jobflow.task.TaskData;
import com.snda.lidejia.jobflow.task.TaskHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author lidejia
 */
public class FtpFetchListBuilder extends TaskHandler<String, FtpFetchList> {

    @Override
    public TaskData<FtpFetchList> handler(TaskData<String> inputs) throws JobFlowException {
        TaskData<FtpFetchList> output = new TaskData<FtpFetchList>();
        String host = getParam("host");
        int port = Integer.parseInt(getParam("port"));
        String userName = getParam("username");
        String password = getParam("password");
        FtpFetchList fetchList = new FtpFetchList(host, userName, password, port);
        String ftpPattern = getParam("ftp_pattern");
        String localPattern = getParam("local_pattern");
        Pattern filterPattern = Pattern.compile(getParam("filter"));
        for (String input : inputs) {
            Matcher matcher = filterPattern.matcher(input);
            if (matcher.find()) {
                input = matcher.group(1);
                String ftpPath = String.format(ftpPattern, input);
                String localPath = String.format(localPattern, input);
                fetchList.addFilePair(new FilePair(ftpPath, localPath));
            }

        }
        output.addData(fetchList);
        return output;
    }
}
